#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
优化的深度分析系统 - 第六步执行模块
专门针对周收益目标(2-3%)和优选5只股票的深度分析
"""

import sys
import os
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from real_data_fetcher import RealDataFetcher

class OptimizedDeepAnalysis:
    """优化的深度分析系统 - 专为周收益目标设计"""
    
    def __init__(self):
        self.data_fetcher = RealDataFetcher()
        
        # 5万资金配置
        self.capital_config = {
            'total_capital': 50000,
            'max_single_loss': 0.05,      # 单只股票最大亏损5%
            'weekly_target_return': 0.025, # 周收益目标2.5%
            'stop_loss_ratio': 0.03,      # 止损比例3%
            'take_profit_ratio': 0.03,    # 止盈比例3%
        }
        
        # 买入时机评估权重
        self.timing_weights = {
            'technical_signal': 0.40,     # 技术信号40%
            'volume_support': 0.25,       # 成交量支撑25%
            'price_position': 0.20,       # 价格位置20%
            'market_sentiment': 0.15,     # 市场情绪15%
        }
        
    def print_header(self, title):
        """打印标题"""
        print(f"\n{'='*80}")
        print(f"🔬 {title}")
        print(f"{'='*80}")
        
    def load_final_ranking(self, filename="optimized_final_ranking.csv"):
        """加载最终排序结果"""
        try:
            df = pd.read_csv(filename)
            print(f"📋 成功加载最终排序结果: {len(df)} 只股票")
            return df.to_dict('records')
        except Exception as e:
            print(f"❌ 加载最终排序结果失败: {e}")
            return []
            
    def get_weekly_data(self, stock_code, weeks=12):
        """获取周K线数据用于周收益分析"""
        try:
            # 获取更多天数的数据以计算周K线
            daily_data = self.data_fetcher.get_stock_data(stock_code, days=weeks*7+10)
            if daily_data is None or daily_data.empty:
                return None
                
            # 转换为周K线数据
            daily_data['date'] = pd.to_datetime(daily_data.index)
            daily_data.set_index('date', inplace=True)
            
            # 按周聚合
            weekly_data = daily_data.resample('W').agg({
                'open': 'first',
                'high': 'max', 
                'low': 'min',
                'close': 'last',
                'volume': 'sum'
            }).dropna()
            
            return weekly_data
            
        except Exception as e:
            print(f"   ❌ 获取 {stock_code} 周K线数据失败: {e}")
            return None
            
    def analyze_weekly_patterns(self, weekly_data):
        """分析周收益模式"""
        try:
            if weekly_data is None or len(weekly_data) < 4:
                return {}
                
            # 计算周收益率
            weekly_returns = weekly_data['close'].pct_change().dropna()
            
            # 周收益统计
            positive_weeks = (weekly_returns > 0).sum()
            total_weeks = len(weekly_returns)
            win_rate = positive_weeks / total_weeks * 100
            
            # 收益分布分析
            avg_positive_return = weekly_returns[weekly_returns > 0].mean() * 100
            avg_negative_return = weekly_returns[weekly_returns < 0].mean() * 100
            
            # 连续性分析
            consecutive_positive = 0
            max_consecutive_positive = 0
            consecutive_negative = 0
            max_consecutive_negative = 0
            
            for ret in weekly_returns:
                if ret > 0:
                    consecutive_positive += 1
                    max_consecutive_positive = max(max_consecutive_positive, consecutive_positive)
                    consecutive_negative = 0
                else:
                    consecutive_negative += 1
                    max_consecutive_negative = max(max_consecutive_negative, consecutive_negative)
                    consecutive_positive = 0
            
            # 周K线形态分析
            recent_weeks = weekly_data.tail(4)
            pattern_score = self.analyze_weekly_pattern_score(recent_weeks)
            
            return {
                'total_weeks_analyzed': total_weeks,
                'win_rate': win_rate,
                'avg_positive_return': avg_positive_return,
                'avg_negative_return': avg_negative_return,
                'max_consecutive_positive': max_consecutive_positive,
                'max_consecutive_negative': max_consecutive_negative,
                'weekly_volatility': weekly_returns.std() * 100,
                'pattern_score': pattern_score,
                'recent_trend': 'up' if weekly_returns.tail(2).mean() > 0 else 'down'
            }
            
        except Exception as e:
            print(f"   ❌ 分析周收益模式失败: {e}")
            return {}
            
    def analyze_weekly_pattern_score(self, recent_weeks):
        """分析最近4周的K线形态评分"""
        try:
            if len(recent_weeks) < 4:
                return 50
                
            score = 50  # 基础分
            
            # 趋势分析
            closes = recent_weeks['close'].values
            if closes[-1] > closes[0]:  # 整体上涨
                score += 20
            
            # 成交量分析
            volumes = recent_weeks['volume'].values
            if volumes[-1] > np.mean(volumes[:-1]):  # 最新一周放量
                score += 15
                
            # 波动性分析
            weekly_ranges = (recent_weeks['high'] - recent_weeks['low']) / recent_weeks['close'] * 100
            if weekly_ranges.mean() < 8:  # 波动不大
                score += 10
            elif weekly_ranges.mean() > 15:  # 波动过大
                score -= 10
                
            # 连续性分析
            weekly_returns = recent_weeks['close'].pct_change().dropna()
            positive_count = (weekly_returns > 0).sum()
            if positive_count >= 2:  # 多数周上涨
                score += 15
                
            return min(100, max(0, score))
            
        except Exception as e:
            print(f"   ❌ 计算周K线形态评分失败: {e}")
            return 50
            
    def identify_optimal_entry_points(self, stock_code, current_price):
        """识别最佳买入时机和价位"""
        try:
            # 获取日K线数据
            daily_data = self.data_fetcher.get_stock_data(stock_code, days=30)
            if daily_data is None or daily_data.empty:
                return {}
                
            # 技术指标计算
            closes = daily_data['close']
            
            # 移动平均线
            ma5 = closes.rolling(5).mean()
            ma10 = closes.rolling(10).mean()
            ma20 = closes.rolling(20).mean()
            
            # RSI
            rsi = self.calculate_rsi(closes, 6)
            
            # 支撑阻力位
            support_resistance = self.find_support_resistance(daily_data, current_price)
            
            # 买入时机评分
            timing_score = self.calculate_timing_score(daily_data, current_price, ma5, ma10, ma20, rsi)
            
            # 价位建议
            entry_prices = self.calculate_entry_prices(current_price, support_resistance)
            
            return {
                'timing_score': timing_score,
                'technical_signals': {
                    'ma5_vs_current': ((current_price - ma5.iloc[-1]) / ma5.iloc[-1] * 100) if not pd.isna(ma5.iloc[-1]) else 0,
                    'ma10_vs_current': ((current_price - ma10.iloc[-1]) / ma10.iloc[-1] * 100) if not pd.isna(ma10.iloc[-1]) else 0,
                    'rsi_6': rsi.iloc[-1] if not pd.isna(rsi.iloc[-1]) else 50,
                },
                'support_resistance': support_resistance,
                'entry_prices': entry_prices,
                'market_position': self.assess_market_position(current_price, closes)
            }
            
        except Exception as e:
            print(f"   ❌ 识别买入时机失败: {e}")
            return {}
            
    def calculate_rsi(self, prices, period=6):
        """计算RSI指标"""
        try:
            delta = prices.diff()
            gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
            loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
            rs = gain / loss
            rsi = 100 - (100 / (1 + rs))
            return rsi
        except:
            return pd.Series([50] * len(prices), index=prices.index)
            
    def find_support_resistance(self, daily_data, current_price):
        """寻找关键支撑阻力位"""
        try:
            highs = daily_data['high']
            lows = daily_data['low']
            
            # 近期高点（阻力位）
            recent_highs = []
            for i in range(2, len(highs) - 2):
                if (highs.iloc[i] > highs.iloc[i-2:i].max() and 
                    highs.iloc[i] > highs.iloc[i+1:i+3].max()):
                    recent_highs.append(highs.iloc[i])
            
            # 近期低点（支撑位）
            recent_lows = []
            for i in range(2, len(lows) - 2):
                if (lows.iloc[i] < lows.iloc[i-2:i].min() and 
                    lows.iloc[i] < lows.iloc[i+1:i+3].min()):
                    recent_lows.append(lows.iloc[i])
            
            # 筛选有效支撑阻力位
            resistance_levels = [r for r in recent_highs if r > current_price and r < current_price * 1.1]
            support_levels = [s for s in recent_lows if s < current_price and s > current_price * 0.9]
            
            return {
                'nearest_resistance': min(resistance_levels) if resistance_levels else current_price * 1.05,
                'nearest_support': max(support_levels) if support_levels else current_price * 0.95,
                'resistance_levels': resistance_levels[:3],
                'support_levels': support_levels[:3]
            }
            
        except Exception as e:
            print(f"   ❌ 寻找支撑阻力位失败: {e}")
            return {
                'nearest_resistance': current_price * 1.05,
                'nearest_support': current_price * 0.95,
                'resistance_levels': [],
                'support_levels': []
            }
            
    def calculate_timing_score(self, daily_data, current_price, ma5, ma10, ma20, rsi):
        """计算买入时机评分"""
        try:
            score = 0
            
            # 技术信号评分 (40%)
            tech_score = 0
            
            # MA信号
            if not pd.isna(ma5.iloc[-1]) and current_price > ma5.iloc[-1]:
                tech_score += 15
            if not pd.isna(ma10.iloc[-1]) and ma5.iloc[-1] > ma10.iloc[-1]:
                tech_score += 15
            if not pd.isna(ma20.iloc[-1]) and ma10.iloc[-1] > ma20.iloc[-1]:
                tech_score += 10
                
            # RSI信号
            current_rsi = rsi.iloc[-1] if not pd.isna(rsi.iloc[-1]) else 50
            if 30 < current_rsi < 70:  # RSI适中
                tech_score += 20
            elif current_rsi < 30:  # 超卖
                tech_score += 30
            elif current_rsi > 80:  # 超买
                tech_score -= 10
                
            # 成交量支撑评分 (25%)
            volumes = daily_data['volume']
            recent_volume = volumes.tail(3).mean()
            avg_volume = volumes.mean()
            
            if recent_volume > avg_volume * 1.2:
                volume_score = 25
            elif recent_volume > avg_volume:
                volume_score = 15
            else:
                volume_score = 5
                
            # 价格位置评分 (20%)
            closes = daily_data['close']
            price_range_20d = closes.tail(20)
            price_position = ((current_price - price_range_20d.min()) / 
                            (price_range_20d.max() - price_range_20d.min()) * 100)
            
            if 20 <= price_position <= 80:  # 位置适中
                position_score = 20
            elif price_position < 30:  # 相对低位
                position_score = 25
            else:  # 相对高位
                position_score = 5
                
            # 市场情绪评分 (15%) - 简化处理
            sentiment_score = 15  # 默认中性
            
            # 综合评分
            total_score = (tech_score * 0.4 + volume_score * 0.25 + 
                         position_score * 0.2 + sentiment_score * 0.15)
            
            return min(100, max(0, total_score))
            
        except Exception as e:
            print(f"   ❌ 计算买入时机评分失败: {e}")
            return 50
            
    def calculate_entry_prices(self, current_price, support_resistance):
        """计算建议买入价位"""
        try:
            nearest_support = support_resistance.get('nearest_support', current_price * 0.95)
            
            # 分批买入价位设计
            entry_prices = {
                'immediate_entry': current_price,  # 立即买入价
                'preferred_entry': current_price * 0.98,  # 优选买入价（回调2%）
                'aggressive_entry': max(nearest_support, current_price * 0.95),  # 积极买入价
                'stop_loss': current_price * (1 - self.capital_config['stop_loss_ratio']),  # 止损价
                'take_profit': current_price * (1 + self.capital_config['take_profit_ratio']),  # 止盈价
            }
            
            return entry_prices
            
        except Exception as e:
            print(f"   ❌ 计算买入价位失败: {e}")
            return {
                'immediate_entry': current_price,
                'preferred_entry': current_price * 0.98,
                'aggressive_entry': current_price * 0.95,
                'stop_loss': current_price * 0.97,
                'take_profit': current_price * 1.03
            }
            
    def assess_market_position(self, current_price, price_series):
        """评估市场位置"""
        try:
            # 计算价格在不同周期的位置
            position_5d = ((current_price - price_series.tail(5).min()) / 
                          (price_series.tail(5).max() - price_series.tail(5).min()) * 100)
            position_20d = ((current_price - price_series.tail(20).min()) / 
                           (price_series.tail(20).max() - price_series.tail(20).min()) * 100)
            
            if position_20d < 30:
                position_desc = "相对低位，适合买入"
            elif position_20d < 70:
                position_desc = "中等位置，谨慎买入"
            else:
                position_desc = "相对高位，等待回调"
                
            return {
                'position_5d': position_5d,
                'position_20d': position_20d,
                'position_description': position_desc
            }
            
        except Exception as e:
            print(f"   ❌ 评估市场位置失败: {e}")
            return {
                'position_5d': 50,
                'position_20d': 50,
                'position_description': "位置不明，谨慎操作"
            }
            
    def generate_trading_plan(self, stock_info, analysis_result):
        """生成具体交易计划"""
        try:
            stock_code = stock_info['code']
            stock_name = stock_info['name']
            current_price = stock_info['current_price']
            comprehensive_score = stock_info['comprehensive_score']
            
            # 基于综合评分分配资金比例
            total_capital = self.capital_config['total_capital']
            cash_reserve = total_capital * 0.1  # 10%现金储备
            investable_amount = total_capital - cash_reserve
            
            # 根据评分和排名分配资金
            ranking = stock_info['rank']
            if ranking == 1:
                allocation_ratio = 0.25  # 第1名分配25%
            elif ranking == 2:
                allocation_ratio = 0.20  # 第2名分配20%
            elif ranking == 3:
                allocation_ratio = 0.18  # 第3名分配18%
            elif ranking == 4:
                allocation_ratio = 0.15  # 第4名分配15%
            else:
                allocation_ratio = 0.12  # 第5名分配12%
                
            # 考虑风险过滤
            if not stock_info.get('pass_filter', True):
                allocation_ratio *= 0.5  # 未通过风险过滤减半配置
                
            allocated_amount = investable_amount * allocation_ratio
            
            # 计算买入股数
            entry_prices = analysis_result.get('entry_prices', {})
            immediate_price = entry_prices.get('immediate_entry', current_price)
            preferred_price = entry_prices.get('preferred_entry', current_price * 0.98)
            
            # 分批买入计划
            batch1_amount = allocated_amount * 0.6  # 第一批60%
            batch2_amount = allocated_amount * 0.4  # 第二批40%
            
            batch1_shares = int(batch1_amount / immediate_price / 100) * 100  # 整手
            batch2_shares = int(batch2_amount / preferred_price / 100) * 100  # 整手
            
            # 实际投资金额
            actual_investment = batch1_shares * immediate_price + batch2_shares * preferred_price
            
            return {
                'allocation_ratio': allocation_ratio,
                'allocated_amount': allocated_amount,
                'trading_plan': {
                    'batch1': {
                        'shares': batch1_shares,
                        'price': immediate_price,
                        'amount': batch1_shares * immediate_price,
                        'timing': '立即执行'
                    },
                    'batch2': {
                        'shares': batch2_shares,
                        'price': preferred_price,
                        'amount': batch2_shares * preferred_price,
                        'timing': '回调时执行'
                    }
                },
                'actual_investment': actual_investment,
                'stop_loss_price': entry_prices.get('stop_loss', current_price * 0.97),
                'take_profit_price': entry_prices.get('take_profit', current_price * 1.03),
                'expected_weekly_return': stock_info.get('expected_return', 1.0),
                'max_loss_amount': actual_investment * 0.05  # 最大亏损金额
            }
            
        except Exception as e:
            print(f"   ❌ 生成交易计划失败: {e}")
            return {}
            
    def deep_analyze_single_stock(self, stock_info):
        """深度分析单只股票"""
        stock_code = stock_info['code']
        stock_name = stock_info['name']
        current_price = stock_info['current_price']
        
        print(f"\n🔬 深度分析: {stock_code} {stock_name}")
        print(f"   📊 综合评分: {stock_info.get('comprehensive_score', 0):.1f}/100")
        print(f"   💰 当前价格: ¥{current_price:.2f}")
        print(f"   📈 周收益预期: {stock_info.get('expected_return', 0):.2f}%")
        print("-" * 70)
        
        # 1. 周收益模式分析
        print(f"\n   📅 周收益模式分析:")
        weekly_data = self.get_weekly_data(stock_code, 12)
        weekly_patterns = self.analyze_weekly_patterns(weekly_data)
        
        if weekly_patterns:
            print(f"      • 分析周期: {weekly_patterns.get('total_weeks_analyzed', 0)} 周")
            print(f"      • 周胜率: {weekly_patterns.get('win_rate', 0):.1f}%")
            print(f"      • 平均周涨幅: {weekly_patterns.get('avg_positive_return', 0):.2f}%")
            print(f"      • 平均周跌幅: {weekly_patterns.get('avg_negative_return', 0):.2f}%")
            print(f"      • 最大连涨周数: {weekly_patterns.get('max_consecutive_positive', 0)}")
            print(f"      • 周K线形态评分: {weekly_patterns.get('pattern_score', 0):.1f}")
            print(f"      • 近期趋势: {weekly_patterns.get('recent_trend', 'unknown')}")
        else:
            print(f"      ❌ 无法获取周K线数据")
            
        # 2. 买入时机分析
        print(f"\n   ⏰ 买入时机分析:")
        entry_analysis = self.identify_optimal_entry_points(stock_code, current_price)
        
        if entry_analysis:
            timing_score = entry_analysis.get('timing_score', 50)
            print(f"      • 买入时机评分: {timing_score:.1f}/100")
            
            signals = entry_analysis.get('technical_signals', {})
            print(f"      • MA5偏离: {signals.get('ma5_vs_current', 0):.1f}%")
            print(f"      • MA10偏离: {signals.get('ma10_vs_current', 0):.1f}%")
            print(f"      • RSI(6): {signals.get('rsi_6', 50):.1f}")
            
            market_pos = entry_analysis.get('market_position', {})
            print(f"      • 20日价格位置: {market_pos.get('position_20d', 50):.1f}%")
            print(f"      • 位置评估: {market_pos.get('position_description', '未知')}")
            
        # 3. 关键价位分析
        print(f"\n   🎯 关键价位分析:")
        if entry_analysis:
            sr_levels = entry_analysis.get('support_resistance', {})
            entry_prices = entry_analysis.get('entry_prices', {})
            
            print(f"      • 当前价格: ¥{current_price:.2f}")
            print(f"      • 最近支撑位: ¥{sr_levels.get('nearest_support', 0):.2f}")
            print(f"      • 最近阻力位: ¥{sr_levels.get('nearest_resistance', 0):.2f}")
            print(f"      • 立即买入价: ¥{entry_prices.get('immediate_entry', 0):.2f}")
            print(f"      • 优选买入价: ¥{entry_prices.get('preferred_entry', 0):.2f}")
            print(f"      • 积极买入价: ¥{entry_prices.get('aggressive_entry', 0):.2f}")
            print(f"      • 建议止损价: ¥{entry_prices.get('stop_loss', 0):.2f}")
            print(f"      • 建议止盈价: ¥{entry_prices.get('take_profit', 0):.2f}")
            
        # 4. 交易计划生成
        print(f"\n   📋 具体交易计划:")
        trading_plan = self.generate_trading_plan(stock_info, entry_analysis)
        
        if trading_plan:
            print(f"      • 资金配置比例: {trading_plan.get('allocation_ratio', 0):.1%}")
            print(f"      • 计划投资金额: {trading_plan.get('allocated_amount', 0):,.0f}元")
            print(f"      • 实际投资金额: {trading_plan.get('actual_investment', 0):,.0f}元")
            
            plan = trading_plan.get('trading_plan', {})
            batch1 = plan.get('batch1', {})
            batch2 = plan.get('batch2', {})
            
            print(f"      • 第一批买入: {batch1.get('shares', 0)}股 × ¥{batch1.get('price', 0):.2f} = {batch1.get('amount', 0):,.0f}元")
            print(f"      • 第二批买入: {batch2.get('shares', 0)}股 × ¥{batch2.get('price', 0):.2f} = {batch2.get('amount', 0):,.0f}元")
            print(f"      • 止损价位: ¥{trading_plan.get('stop_loss_price', 0):.2f}")
            print(f"      • 止盈价位: ¥{trading_plan.get('take_profit_price', 0):.2f}")
            print(f"      • 最大亏损: {trading_plan.get('max_loss_amount', 0):,.0f}元")
            
        # 5. 操作建议
        print(f"\n   💡 操作建议:")
        
        # 基于时机评分给出建议
        timing_score = entry_analysis.get('timing_score', 50) if entry_analysis else 50
        
        if timing_score >= 80:
            action_advice = "强烈建议买入，时机excellent"
        elif timing_score >= 70:
            action_advice = "建议买入，时机良好"
        elif timing_score >= 60:
            action_advice = "可考虑买入，谨慎操作"
        elif timing_score >= 50:
            action_advice = "观望为主，等待更好时机"
        else:
            action_advice = "不建议买入，等待改善"
            
        print(f"      • 操作建议: {action_advice}")
        print(f"      • 监控要点: 关注成交量变化和突破情况")
        print(f"      • 调整信号: RSI超买(>80)或跌破止损位")
        
        # 返回完整分析结果
        result = {
            **stock_info,
            'deep_analysis': {
                'weekly_patterns': weekly_patterns,
                'entry_analysis': entry_analysis,
                'trading_plan': trading_plan,
                'timing_score': timing_score,
                'action_advice': action_advice
            }
        }
        
        return result
        
    def run_deep_analysis(self):
        """运行深度分析系统"""
        self.print_header("第六步：深度分析优选股票 - 周收益操作指导")
        
        print(f"🎯 分析目标: 优选5只股票的具体操作指导")
        print(f"💰 资金规模: {self.capital_config['total_capital']:,}元")
        print(f"📊 周收益目标: {self.capital_config['weekly_target_return']:.1%}")
        
        # 加载最终排序结果
        final_ranking = self.load_final_ranking()
        if not final_ranking:
            print("❌ 无法加载最终排序结果，请先执行第五步")
            return []
            
        # 选择优选的5只股票（通过风险过滤的前5只）
        filtered_stocks = [stock for stock in final_ranking if stock.get('pass_filter', False)]
        top5_stocks = filtered_stocks[:5]
        
        if len(top5_stocks) < 5:
            print(f"⚠️ 只有 {len(top5_stocks)} 只股票通过风险过滤，将分析这些股票")
            
        print(f"\n📋 深度分析优选股票:")
        for i, stock in enumerate(top5_stocks, 1):
            print(f"   {i}. {stock['code']} {stock['name']} - 综合评分: {stock['comprehensive_score']:.1f}")
            
        deep_analysis_results = []
        
        for i, stock_info in enumerate(top5_stocks, 1):
            print(f"\n[{i}/{len(top5_stocks)}] 深度分析进度")
            
            try:
                result = self.deep_analyze_single_stock(stock_info)
                if result:
                    deep_analysis_results.append(result)
            except Exception as e:
                print(f"   ❌ 分析失败: {e}")
                continue
                
        # 生成深度分析总结报告
        self.generate_comprehensive_report(deep_analysis_results)
        
        return deep_analysis_results
        
    def generate_comprehensive_report(self, deep_analysis_results):
        """生成综合深度分析报告"""
        self.print_header("📊 深度分析综合报告")
        
        if not deep_analysis_results:
            print("❌ 没有完成深度分析的股票")
            return
            
        print(f"📈 深度分析股票数量: {len(deep_analysis_results)}")
        
        # 1. 买入时机评分排序
        timing_ranking = sorted(deep_analysis_results, 
                               key=lambda x: x.get('deep_analysis', {}).get('timing_score', 0), 
                               reverse=True)
        
        print(f"\n⏰ 买入时机评分排序:")
        print(f"{'排名':<4} {'代码':<8} {'名称':<10} {'时机评分':<8} {'操作建议':<15}")
        print("-" * 60)
        
        for i, result in enumerate(timing_ranking, 1):
            deep_data = result.get('deep_analysis', {})
            timing_score = deep_data.get('timing_score', 0)
            action_advice = deep_data.get('action_advice', '未知')[:12]
            
            print(f"{i:<4} {result['code']:<8} {result['name']:<10} "
                  f"{timing_score:<8.1f} {action_advice:<15}")
                  
        # 2. 投资组合总体配置
        print(f"\n💼 投资组合总体配置:")
        
        total_investment = 0
        total_expected_return = 0
        
        for result in deep_analysis_results:
            deep_data = result.get('deep_analysis', {})
            trading_plan = deep_data.get('trading_plan', {})
            actual_investment = trading_plan.get('actual_investment', 0)
            expected_return = result.get('expected_return', 0)
            
            total_investment += actual_investment
            total_expected_return += actual_investment * expected_return / 100
            
        print(f"   💰 总计划投资: {total_investment:,.0f}元")
        print(f"   💵 剩余现金: {50000 - total_investment:,.0f}元")
        print(f"   📈 组合预期周收益: {total_expected_return:,.0f}元 ({total_expected_return/50000*100:.2f}%)")
        
        # 3. 具体操作时间表
        print(f"\n📅 操作时间表建议:")
        
        # 按时机评分排序执行
        immediate_actions = []
        wait_actions = []
        
        for result in timing_ranking:
            deep_data = result.get('deep_analysis', {})
            timing_score = deep_data.get('timing_score', 0)
            
            if timing_score >= 70:
                immediate_actions.append(result)
            else:
                wait_actions.append(result)
                
        if immediate_actions:
            print(f"   🚀 立即执行 ({len(immediate_actions)}只):")
            for result in immediate_actions:
                trading_plan = result.get('deep_analysis', {}).get('trading_plan', {})
                batch1 = trading_plan.get('batch1', {})
                print(f"      • {result['code']} {result['name']}: "
                      f"{batch1.get('shares', 0)}股 × ¥{batch1.get('price', 0):.2f}")
                      
        if wait_actions:
            print(f"   ⏰ 等待时机 ({len(wait_actions)}只):")
            for result in wait_actions:
                deep_data = result.get('deep_analysis', {})
                entry_analysis = deep_data.get('entry_analysis', {})
                entry_prices = entry_analysis.get('entry_prices', {})
                preferred_price = entry_prices.get('preferred_entry', 0)
                print(f"      • {result['code']} {result['name']}: "
                      f"等待回调至 ¥{preferred_price:.2f}")
                      
        # 4. 风险控制要点
        print(f"\n⚠️ 风险控制要点:")
        print(f"   • 单只股票最大亏损: 不超过投资金额的5%")
        print(f"   • 组合止损线: 总亏损超过{50000*0.03:,.0f}元时考虑减仓")
        print(f"   • 监控频率: 每日收盘后检查，重点关注成交量和技术指标")
        print(f"   • 调整信号: RSI超买、跌破支撑位、基本面恶化")
        
        # 5. 操作注意事项
        print(f"\n📝 操作注意事项:")
        print(f"   • 分批建仓: 避免一次性满仓，保留调整空间")
        print(f"   • 止损纪律: 严格执行止损，不可侥幸心理")
        print(f"   • 获利了结: 达到止盈目标及时获利了结")
        print(f"   • 资金管理: 保持10%现金储备，灵活应对机会")
        print(f"   • 心态管理: 保持理性，不因短期波动影响判断")
        
    def save_deep_analysis_results(self, deep_analysis_results, filename="optimized_deep_analysis_results.csv"):
        """保存深度分析结果"""
        if not deep_analysis_results:
            print("❌ 没有分析结果需要保存")
            return None
            
        try:
            # 构建保存数据
            save_data = []
            for i, result in enumerate(deep_analysis_results, 1):
                deep_data = result.get('deep_analysis', {})
                weekly_patterns = deep_data.get('weekly_patterns', {})
                entry_analysis = deep_data.get('entry_analysis', {})
                trading_plan = deep_data.get('trading_plan', {})
                
                save_record = {
                    'rank': i,
                    'code': result['code'],
                    'name': result['name'],
                    'current_price': result['current_price'],
                    'comprehensive_score': result['comprehensive_score'],
                    'timing_score': deep_data.get('timing_score', 0),
                    'weekly_win_rate': weekly_patterns.get('win_rate', 0),
                    'avg_positive_return': weekly_patterns.get('avg_positive_return', 0),
                    'pattern_score': weekly_patterns.get('pattern_score', 0),
                    'allocated_amount': trading_plan.get('allocated_amount', 0),
                    'actual_investment': trading_plan.get('actual_investment', 0),
                    'stop_loss_price': trading_plan.get('stop_loss_price', 0),
                    'take_profit_price': trading_plan.get('take_profit_price', 0),
                    'action_advice': deep_data.get('action_advice', ''),
                    'expected_return': result.get('expected_return', 0),
                    'analysis_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                }
                save_data.append(save_record)
                
            df = pd.DataFrame(save_data)
            df.to_csv(filename, index=False, encoding='utf-8-sig')
            print(f"\n💾 深度分析结果已保存到 {filename}")
            return filename
            
        except Exception as e:
            print(f"❌ 保存深度分析结果失败: {e}")
            return None

    def load_selected_stocks(self, filename):
        """加载优选股票数据"""
        try:
            if os.path.exists(filename):
                df = pd.read_csv(filename)
                print(f"✅ 成功加载优选股票数据: {len(df)} 只")
                return df.to_dict('records')
            else:
                print(f"❌ 文件不存在: {filename}")
                return []
        except Exception as e:
            print(f"❌ 加载优选股票数据失败: {e}")
            return []
    
    def analyze_stock(self, stock_info):
        """深度分析单只股票"""
        try:
            stock_code = stock_info['code']
            stock_name = stock_info['name']
            
            print(f"🔍 深度分析: {stock_code} - {stock_name}")
            
            # 获取周K线数据
            weekly_data = self.get_weekly_data(stock_code)
            if weekly_data is None:
                return None
                
            # 分析周收益模式
            weekly_patterns = self.analyze_weekly_patterns(weekly_data)
            
            # 评估买入时机
            timing_score = self.evaluate_buy_timing(stock_code, weekly_data)
            
            # 计算风险收益比
            risk_reward = self.calculate_risk_reward_ratio(weekly_data)
            
            # 生成操作建议
            operation_advice = self.generate_operation_advice(
                stock_code, weekly_patterns, timing_score, risk_reward
            )
            
            return {
                'stock_code': stock_code,
                'stock_name': stock_name,
                'weekly_return_expectation': weekly_patterns.get('avg_positive_return', 0),
                'risk_level': self.classify_risk_level(risk_reward),
                'confidence': timing_score / 100,
                'buy_timing': operation_advice.get('buy_timing', '观望'),
                'stop_loss': operation_advice.get('stop_loss', 0),
                'take_profit': operation_advice.get('take_profit', 0),
                'weekly_patterns': weekly_patterns,
                'timing_score': timing_score,
                'risk_reward': risk_reward,
                'operation_advice': operation_advice
            }
            
        except Exception as e:
            print(f"❌ 深度分析股票 {stock_info.get('code', 'N/A')} 失败: {e}")
            return None
    
    def analyze_portfolio(self, selected_stocks):
        """批量深度分析投资组合"""
        try:
            results = []
            
            print(f"🔄 开始批量分析 {len(selected_stocks)} 只股票...")
            
            for i, stock in enumerate(selected_stocks, 1):
                print(f"\n📊 进度: {i}/{len(selected_stocks)}")
                
                analysis_result = self.analyze_stock(stock)
                if analysis_result:
                    results.append(analysis_result)
                    
            print(f"\n✅ 批量分析完成，成功分析 {len(results)} 只股票")
            return results
            
        except Exception as e:
            print(f"❌ 批量分析失败: {e}")
            return []
    
    def generate_operation_suggestions(self, analysis_results):
        """生成操作建议"""
        try:
            suggestions = []
            
            for result in analysis_results:
                stock_code = result['stock_code']
                timing_score = result['timing_score']
                confidence = result['confidence']
                
                # 根据时机分数和置信度生成建议
                if timing_score >= 80 and confidence >= 0.7:
                    action = '立即买入'
                    reason = f'时机分数{timing_score}，置信度{confidence:.1%}'
                elif timing_score >= 60 and confidence >= 0.5:
                    action = '分批买入'
                    reason = f'时机适中，可分批建仓'
                elif timing_score >= 40:
                    action = '关注观望'
                    reason = f'时机一般，继续观察'
                else:
                    action = '暂不买入'
                    reason = f'时机不佳，等待更好机会'
                    
                suggestions.append({
                    'stock_code': stock_code,
                    'action': action,
                    'reason': reason,
                    'timing_score': timing_score,
                    'confidence': confidence
                })
                
            return suggestions
            
        except Exception as e:
            print(f"❌ 生成操作建议失败: {e}")
            return []
    
    def generate_risk_control_suggestions(self, analysis_results):
        """生成风险控制建议"""
        try:
            controls = []
            
            # 整体风险控制
            high_risk_count = sum(1 for r in analysis_results if r['risk_level'] == '高风险')
            if high_risk_count > 2:
                controls.append({
                    'type': '组合风险',
                    'suggestion': f'高风险股票过多({high_risk_count}只)，建议减少高风险配置'
                })
            
            # 单只股票风险控制
            for result in analysis_results:
                stock_code = result['stock_code']
                risk_level = result['risk_level']
                
                if risk_level == '高风险':
                    controls.append({
                        'type': '个股风险',
                        'suggestion': f'{stock_code}风险较高，建议降低仓位或设置较紧止损'
                    })
                elif result['confidence'] < 0.5:
                    controls.append({
                        'type': '置信度',
                        'suggestion': f'{stock_code}置信度较低，建议观望或小仓位试探'
                    })
                    
            # 资金管理建议
            controls.append({
                'type': '资金管理',
                'suggestion': '建议分3-5次分批建仓，避免一次性满仓'
            })
            
            return controls
            
        except Exception as e:
            print(f"❌ 生成风险控制建议失败: {e}")
            return []
    
    def save_analysis_results(self, results, filename):
        """保存分析结果到CSV"""
        try:
            if not results:
                return False
                
            # 转换为DataFrame
            df_data = []
            for result in results:
                df_data.append({
                    'stock_code': result['stock_code'],
                    'stock_name': result['stock_name'],
                    'weekly_return_expectation': result['weekly_return_expectation'],
                    'risk_level': result['risk_level'],
                    'confidence': result['confidence'],
                    'buy_timing': result['buy_timing'],
                    'stop_loss': result['stop_loss'],
                    'take_profit': result['take_profit'],
                    'timing_score': result['timing_score']
                })
            
            df = pd.DataFrame(df_data)
            df.to_csv(filename, index=False, encoding='utf-8')
            
            print(f"✅ 分析结果已保存到: {filename}")
            return True
            
        except Exception as e:
            print(f"❌ 保存分析结果失败: {e}")
            return False
    
    def generate_investment_report(self, analysis_results, operation_suggestions, risk_control):
        """生成投资报告"""
        try:
            report = f"""# 深度分析实战操作报告

## 📊 分析概况
- 分析时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
- 分析股票数量: {len(analysis_results)}
- 投资资金: 5万元
- 投资目标: 周收益2-3%

## 🎯 投资组合分析

"""
            
            # 添加每只股票的分析结果
            for result in analysis_results:
                report += f"""### {result['stock_code']} - {result['stock_name']}

**基本分析:**
- 周收益预期: {result['weekly_return_expectation']:.2f}%
- 风险等级: {result['risk_level']}
- 置信度: {result['confidence']:.1%}
- 时机分数: {result['timing_score']:.1f}

**操作建议:**
- 买入时机: {result['buy_timing']}
- 建议止损: {result['stop_loss']:.2f}%
- 建议止盈: {result['take_profit']:.2f}%

---

"""
            
            # 添加操作建议
            report += "## 💡 操作建议汇总\n\n"
            for suggestion in operation_suggestions:
                report += f"- **{suggestion['stock_code']}**: {suggestion['action']} ({suggestion['reason']})\n"
            
            # 添加风险控制
            report += "\n## ⚠️ 风险控制建议\n\n"
            for control in risk_control:
                report += f"- **{control['type']}**: {control['suggestion']}\n"
            
            report += f"""

## 📈 投资策略要点

1. **分批建仓**: 建议分3-5次建仓，避免一次性满仓
2. **严格止损**: 单只股票亏损达到3%立即止损
3. **及时止盈**: 单只股票盈利达到3%考虑止盈
4. **动态调整**: 根据市场变化及时调整仓位
5. **风险监控**: 密切关注高风险股票的表现

## 🎯 预期收益目标

- 周收益目标: 2-3%
- 最大回撤控制: 不超过3%
- 成功率预期: 70%以上

---
*本报告基于历史数据和技术分析生成，仅供参考，投资有风险，决策需谨慎。*
"""
            
            return report
            
        except Exception as e:
            print(f"❌ 生成投资报告失败: {e}")
            return None

    def classify_risk_level(self, risk_reward):
        """分类风险等级"""
        try:
            volatility = risk_reward.get('volatility', 0)
            
            if volatility < 15:
                return '低风险'
            elif volatility < 25:
                return '中风险'
            else:
                return '高风险'
                
        except:
            return '中风险'
    
    def evaluate_buy_timing(self, stock_code, weekly_data):
        """评估买入时机"""
        try:
            # 简化的时机评估
            if weekly_data is None or len(weekly_data) < 4:
                return 50
                
            # 基于最近的价格趋势
            recent_closes = weekly_data['close'].tail(4)
            
            score = 50  # 基础分
            
            # 上升趋势加分
            if recent_closes.iloc[-1] > recent_closes.iloc[0]:
                score += 20
                
            # 成交量配合
            recent_volumes = weekly_data['volume'].tail(4)
            if recent_volumes.iloc[-1] > recent_volumes.mean():
                score += 15
                
            # 价格位置（相对于最近高点）
            recent_high = weekly_data['high'].tail(12).max()
            current_price = recent_closes.iloc[-1]
            price_position = current_price / recent_high
            
            if price_position > 0.95:  # 接近高点
                score -= 10
            elif price_position < 0.85:  # 相对低位
                score += 10
                
            return max(0, min(100, score))
            
        except Exception as e:
            print(f"❌ 评估买入时机失败: {e}")
            return 50
    
    def calculate_risk_reward_ratio(self, weekly_data):
        """计算风险收益比"""
        try:
            if weekly_data is None or len(weekly_data) < 4:
                return {'volatility': 20, 'risk_reward_ratio': 1.0}
                
            # 计算收益率
            returns = weekly_data['close'].pct_change().dropna()
            
            # 计算波动率
            volatility = returns.std() * 100
            
            # 计算风险收益比
            avg_return = returns.mean() * 100
            risk_reward_ratio = abs(avg_return / volatility) if volatility > 0 else 1.0
            
            return {
                'volatility': volatility,
                'avg_return': avg_return,
                'risk_reward_ratio': risk_reward_ratio
            }
            
        except Exception as e:
            print(f"❌ 计算风险收益比失败: {e}")
            return {'volatility': 20, 'risk_reward_ratio': 1.0}
    
    def generate_operation_advice(self, stock_code, weekly_patterns, timing_score, risk_reward):
        """生成操作建议"""
        try:
            # 买入时机判断
            if timing_score >= 80:
                buy_timing = '立即买入'
            elif timing_score >= 60:
                buy_timing = '分批买入'
            elif timing_score >= 40:
                buy_timing = '关注观望'
            else:
                buy_timing = '暂不买入'
                
            # 止损止盈设置
            volatility = risk_reward.get('volatility', 20)
            
            # 动态止损：基于波动率调整
            if volatility < 15:
                stop_loss = 2.5
                take_profit = 3.5
            elif volatility < 25:
                stop_loss = 3.0
                take_profit = 3.0
            else:
                stop_loss = 3.5
                take_profit = 2.5
                
            return {
                'buy_timing': buy_timing,
                'stop_loss': stop_loss,
                'take_profit': take_profit,
                'position_size': '20%',  # 建议仓位
                'holding_period': '1周',
                'review_frequency': '每日'
            }
            
        except Exception as e:
            print(f"❌ 生成操作建议失败: {e}")
            return {
                'buy_timing': '观望',
                'stop_loss': 3.0,
                'take_profit': 3.0,
                'position_size': '20%',
                'holding_period': '1周',
                'review_frequency': '每日'
            }
